/**
* @file   FileWriter.cpp
* @brief  Implementation file for class FileWriter
* @date   2011-04-12 19:13:30
* @author Yanze Lian
* @email  <yanzel@gmail.com>
*/

#include "stdafx.h"
#include "FileWriter.h"
#include <streams.h>
#include <uuids.h>
#include "safe_defs.h"
#include "ProfileManager.h"
#include "DxFuncs.h"
#include "PubDefs.h"


FileWriter::FileWriter()
{
	m_pASFWriter = NULL;
	m_pFileSink = NULL;
	m_pConfigAsfWriter = NULL;
}

FileWriter::~FileWriter()
{
	UnInit();
}

IBaseFilter* FileWriter::GetPointer()
{
	return m_pASFWriter;
}

HRESULT FileWriter::Init(IGraphBuilder* pGraph, CString fileName)
{
	if(pGraph == NULL || fileName == _T(""))
		return E_POINTER;

	HRESULT hr = S_OK;
	IWMProfile* pProfile = NULL;
	do 
	{
		UnInit();
		hr = DxFuncs::CreateFilter(CLSID_WMAsfWriter, &m_pASFWriter);
		BREAK_IF_FAILED(hr, _T("FileWriter CreateFilter"));

		hr = m_pASFWriter->QueryInterface(IID_IFileSinkFilter, (void **) &m_pFileSink);
		BREAK_IF_FAILED(hr, _T("FileWriter QueryInterface IID_IFileSinkFilter"));

		WCHAR wFile[MAX_PATH];
		CStringToWChar(wFile, MAX_PATH, fileName);
		hr = m_pFileSink->SetFileName(wFile, NULL);
		BREAK_IF_FAILED(hr, _T("FileWriter SetFileName"));

		hr = pGraph->AddFilter(m_pASFWriter, L"Mux");
		BREAK_IF_FAILED(hr, _T("FileWriter AddFilter"));

		hr = m_pASFWriter->QueryInterface(IID_IConfigAsfWriter, (void **) &m_pConfigAsfWriter);
		BREAK_IF_FAILED(hr, _T("FileWriter QueryInterface IID_IConfigAsfWriter"));

		ProfileManager profileManager;
		hr = profileManager.CreateNewVideoProfile(pProfile);
		BREAK_IF_FAILED(hr, _T("FileWriter CreateNewVideoProfile"));
		
		// Note that the ASF writer will not run if the number of streams
		// does not match the profile.
		hr = m_pConfigAsfWriter->ConfigureFilterUsingProfile(pProfile);
		BREAK_IF_FAILED(hr, _T("FileWriter ConfigureFilterUsingProfile"));

	} while (false);
	SAFE_RELEASE(pProfile);
	if(FAILED(hr))
	{
		UnInit();
	}
	return hr;
}

void FileWriter::UnInit()
{
	SAFE_RELEASE(m_pConfigAsfWriter);
	SAFE_RELEASE(m_pFileSink);
	SAFE_RELEASE(m_pASFWriter);
}



